#!/usr/bin/env/ python

import sys
import argparse
import yaml

from httpspy.core.http_sniffer import HTTPSniffer
from httpspy.core.module_manager import ModuleManager

# Load modules
import httpspy.modules

def parse_arguments():

	parser = argparse.ArgumentParser(description='A very basic http sniffer')

 	group = parser.add_mutually_exclusive_group()
	group.add_argument('--pcapfile', help='read a tcp stream from a file')
 	group.add_argument('--device', help='set the device to sniff')

	parser.add_argument('--filter', help='set the filter (see man tcpdump)',
		default='')
	parser.add_argument('--list-modules', help='List availables modules',
		action='store_true');
	parser.add_argument('--help-module', help='Show help for a module');
	#parser.add_argument('--modules_file', help='File with configured modules');

	return parser.parse_args()

def main(*args):

	# Reading the arguments
	args = parse_arguments() 

	# Listing the availables modules
	if args.list_modules:
		print "Modules availables: \n"
		for module_name in ModuleManager.list_modules():
			print "- " + module_name
		print "\nUse '--help-module MODULE_NAME' to see help about a module"
		sys.exit(0)

	# Listing the help about a module
	if args.help_module:
		ModuleManager.get_module(args.help_module).help()
		sys.exit(0)

	# Load the yaml file into a dict
	stream = file(args.modules_file, 'r')
	modules_conf = yaml.load(stream)
	
	modules = []
	for module_name in modules_conf.keys():
		modules.append(ModuleManager.get_module(module_name)(modules_conf[modules_name]))
	
	def log_with_modules(http_stream):
		for module in modules:
			module.log_stream(http_stream)

	# Sniffer initializing
	HTTPSniffer.set_params(
		callback=log_with_modules,
		device=args.device,
		pcapfile=args.pcapfile, 
		filter=args.filter,
	)
		
	# Start sniffing 
	HTTPSniffer.start();
	
	sys.exit(0)


if __name__ == '__main__' : main (sys.argv)
